<template>
  <div class="common-layout">
    <el-container>
      <!-- 侧边栏：课程列表 -->
      <el-aside width="300px" class="task-list">
        <p>课程列表</p>
        <div
          v-for="(task, index) in taskList"
          :key="index"
          style="margin-right: 20px"
        >
          <el-card
            :style="{
              backgroundColor:
                selectedTaskId === task.taskId ? '#C0C5CC' : 'white',
              color: selectedTaskId === task.taskId ? 'white' : 'black'
            }"
            style="max-width: 280px; margin-top: 20px; margin-left: 40px"
          >
            <template #header>
              <div class="card-header">
                <span>{{ task.taskName }}</span>
              </div>
            </template>
            <div class="text item" style="text-align: center">
              <div class="mb-4">
                <el-button
                  type="success"
                  @click="taskAllComment(task.taskId)"
                  v-loading.fullscreen.lock="fullscreenLoading"
                  >查看评论详情</el-button
                >
              </div>
            </div>
          </el-card>
        </div>
      </el-aside>
      <!-- 主区域：评论区 -->
      <div
        id="comment-area-wrapper"
        style="margin-left: 20px; max-width: 1080px; min-height: 600px"
      >
        <el-main class="comment-section">
          <el-card
            v-if="selectedTaskId"
            style="width: 900px; min-height: 600px"
          >
            <template #header>
              <div class="card-header">
                <span v-html="currentTitle.replace(/\n/g, '<br>')"></span>
              </div>
            </template>
            <div style="text-align: center; margin-top: 20px; font-size: 20px">
              评论区
              <span style="font-size: 16px; color: #999; margin-left: 10px"
                >(点击用户名可以回复)</span
              >
            </div>
            <el-divider></el-divider>
            <div>
              <div style="display: inline-flex">
                <el-input
                  v-model="input"
                  maxlength="250"
                  show-word-limit
                  type="textarea"
                  placeholder="写点什么..."
                  style="
                    width: 450px;
                    height: 40px;
                    margin-left: auto;
                    margin-right: 20px;
                  "
                  clearable
                  @input="timeEffectInput"
                >
                </el-input>
                <el-upload
                  :http-request="customUpload"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload"
                  list-type="text"
                  :limit="1"
                  :auto-upload="true"
                >
                  <el-icon style="font-size: 30px; margin-top: 10px"
                    ><Picture
                  /></el-icon>
                </el-upload>
                <el-button
                  @click="addnewComment(taskID)"
                  :disabled="isSubmitting"
                  style="margin-top: 10px; margin-left: 10px"
                >
                  发表评论
                </el-button>
              </div>

              <el-divider></el-divider>
              <div v-if="commentList.length > 0">
                <div id="comment-area-wrapper1">
                  <div v-for="(comment, index) in commentList" :key="index">
                    <el-descriptions title="">
                      <el-descriptions-item>
                        <div
                          style="
                            color: #e4e4e4;
                            font-size: 30px;
                            margin-left: 600px;
                            margin-right: 20px;
                          "
                        >
                          {{
                            comment.topButtonText == '取消置顶'
                              ? '⭐-置顶评论-⭐'
                              : ''
                          }}
                        </div>
                        <span
                          style="
                            font-size: 20px;
                            margin-left: 10px;
                            font-family: 幼圆, serif;
                            padding: 2px;
                            margin-right: 10px;
                            background-color: #b9bfbb;
                          "
                        >
                          {{ comment.username }}
                        </span>
                        <el-button
                          plain
                          @click="dialogVisible[comment.id] = true"
                          style="
                            font-size: 10px;
                            width: 12px;
                            border: none;
                            background-color: transparent;
                            color: #758e67;
                          "
                        >
                          回复
                        </el-button>
                        <el-dialog
                          v-model="dialogVisible[comment.id]"
                          title="回复"
                          width="500"
                        >
                          <span>回复@{{ comment.username }}</span>
                          <span>
                            <el-input
                              v-model="input1"
                              maxlength="250"
                              show-word-limit
                              style="
                                width: 320px;
                                margin-left: 20px;
                                height: 40px;
                              "
                              placeholder="回复点什么..."
                              type="textarea"
                            />
                          </span>
                          <el-upload
                            :http-request="customUpload"
                            :on-success="handleUploadSuccess"
                            :before-upload="beforeUpload"
                            list-type="text"
                            :limit="1"
                            :auto-upload="true"
                          >
                            <el-icon style="font-size: 30px; margin-top: 10px"
                              ><Picture
                            /></el-icon>
                          </el-upload>
                          <template #footer>
                            <div class="dialog-footer">
                              <el-button
                                type="primary"
                                @click="
                                  handleCommentReplyComment(
                                    taskID,
                                    comment.id,
                                    comment.level,
                                    comment.parentCommentId
                                  )
                                "
                              >
                                回复
                              </el-button>
                            </div>
                          </template>
                        </el-dialog>
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions title="">
                      <el-descriptions-item>
                        <span
                          v-html="comment.content.replace(/\n/g, '<br>')"
                          style="font-size: 18px; margin-left: 30px"
                        ></span>
                        <template v-if="comment.commentPic">
                          <span class="demo-image__preview"></span>
                          <el-image
                            style="
                              cursor: pointer;
                              width: 100px;
                              height: 100px;
                              margin-left: 30px;
                            "
                            :src="comment.commentPic"
                            fit="cover"
                            :preview-src-list="[comment.commentPic]"
                          ></el-image>
                        </template>
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions title="">
                      <el-descriptions-item>
                        【{{ formatTime(comment.createTime) }}】
                        <el-button
                          type="info"
                          plain
                          @click="toggleReply(comment)"
                          style="
                            background-color: transparent;
                            color: #409eff;
                            margin-left: 100px;
                          "
                        >
                          查看回复
                        </el-button>
                        <el-button
                          type="info"
                          plain
                          @click="toAddLike(comment.id)"
                          style="
                            background-color: transparent;
                            margin-left: 10px;
                            border: none;
                          "
                        >
                          {{ likeList[comment.id] == 1 ? '❤️' : '♡' }}
                        </el-button>
                        <span
                          v-for="countList in likeCountList"
                          :key="countList.commentId"
                        >
                          <span v-if="countList.commentId == comment.id">
                            {{ countList.likeCount }}人赞了该评论
                          </span>
                        </span>
                      </el-descriptions-item>
                    </el-descriptions>
                    <!-- 回复区域 -->
                    <el-card
                      :class="{ 'top-comment': comment.isTop }"
                      v-if="comment.showReply"
                      style="
                        max-width: 800px;
                        background-color: #f2f2f2;
                        margin-top: 20px;
                        padding: 10px;
                      "
                    >
                      <div
                        v-if="comment.replyList && comment.replyList.length > 0"
                      >
                        <h1>回复数: {{ comment.replyList.length }}</h1>
                        <el-divider></el-divider>
                        <div v-for="reply in comment.replyList" :key="reply.id">
                          <div class="text item">
                            <span
                              style="
                                font-size: 20px;
                                margin-left: 10px;
                                font-family: 幼圆, serif;
                                padding: 2px;
                                margin-right: 10px;
                                background-color: #b9bfbb;
                              "
                            >
                              {{ reply.username }}
                            </span>
                            <el-button
                              plain
                              @click="dialogVisible[reply.id] = true"
                              style="
                                font-size: 10px;
                                width: 12px;
                                border: none;
                                background-color: transparent;
                                color: #758e67;
                              "
                            >
                              回复
                            </el-button>
                            <el-dialog
                              v-model="dialogVisible[reply.id]"
                              title="回复"
                              width="500"
                            >
                              <span> 回复@{{ reply.username }} </span>
                              <span>
                                <el-input
                                  v-model="input1"
                                  style="width: 320px; margin-left: 20px"
                                  maxlength="250"
                                  show-word-limit
                                  placeholder="回复点什么..."
                                  type="textarea"
                                />
                              </span>
                              <el-upload
                                :http-request="customUpload"
                                :on-success="handleUploadSuccess"
                                :before-upload="beforeUpload"
                                list-type="text"
                                :limit="1"
                                :auto-upload="true"
                              >
                                <el-icon
                                  style="font-size: 30px; margin-top: 10px"
                                  ><Picture
                                /></el-icon>
                              </el-upload>
                              <template #footer>
                                <div class="dialog-footer">
                                  <el-button
                                    type="primary"
                                    @click="
                                      handleReplyReplyComment(
                                        taskID,
                                        reply.id,
                                        reply.level,
                                        reply.parentCommentId
                                      )
                                    "
                                  >
                                    回复
                                  </el-button>
                                </div>
                              </template>
                            </el-dialog>
                            <span v-if="reply.level > 2" style="color: #409eff">
                              <span style="margin-left: 10px; color: #232323"
                                >回复@</span
                              >{{ reply.replyUsername }}
                            </span>
                            <el-button
                              v-if="reply.level > 1"
                              type="info"
                              plain
                              @click="showRelatedDialog(reply.id)"
                              style="
                                background-color: transparent;
                                color: #409eff;
                                margin-left: 10px;
                                text-align: justify;
                              "
                            >
                              查看对话
                            </el-button>
                            <el-dialog
                              v-model="relatedDialogVisible"
                              title="对话详情"
                              width="1000"
                              :data-comment-id="currentCommentIdForDialog"
                              @close="handleDialogClose"
                            >
                              <el-divider></el-divider>
                              <div
                                v-for="(chatComment, chatIndex) in chatList"
                                :key="chatIndex"
                              >
                                <el-descriptions title="">
                                  <el-descriptions-item>
                                    <div
                                      style="font-size: 18px; margin-left: 10px"
                                    >
                                      {{ chatComment.username }}
                                    </div>
                                    <span
                                      style="
                                        font-size: 18px;
                                        margin-left: 30px;
                                        margin-top: 10px;
                                      "
                                    >
                                      |-------
                                    </span>

                                    <span
                                      v-html="
                                        chatComment.content.replace(
                                          /\n/g,
                                          '<br>'
                                        )
                                      "
                                      style="
                                        font-size: 18px;
                                        margin-left: 60px;
                                        margin-top: 10px;
                                      "
                                    ></span>
                                    <span v-if="chatComment.commentPic">
                                      <span class="demo-image__preview"></span>
                                      <el-image
                                        style="
                                          cursor: pointer;
                                          width: 100px;
                                          height: 100px;
                                          margin-left: 140px;
                                          margin-top: 10px;
                                        "
                                        :src="chatComment.commentPic"
                                        fit="cover"
                                        :preview-src-list="[
                                          chatComment.commentPic
                                        ]"
                                      />
                                    </span>
                                    <div style="text-align: right">
                                      {{ formatTime(chatComment.createTime) }}
                                    </div>
                                  </el-descriptions-item>
                                </el-descriptions>
                                <el-divider></el-divider>
                              </div>
                            </el-dialog>
                            <el-divider></el-divider>
                            <p style="margin-left: 100px">
                              <span
                                v-html="reply.content.replace(/\n/g, '<br>')"
                              ></span>
                            </p>
                            <span v-if="reply.commentPic">
                              <span class="demo-image__preview"></span>
                              <el-image
                                style="
                                  cursor: pointer;
                                  width: 100px;
                                  height: 100px;
                                  margin-left: 100px;
                                "
                                :src="reply.commentPic"
                                fit="cover"
                                :preview-src-list="[reply.commentPic]"
                              />
                            </span>
                            <div style="display: flex">
                              <el-button
                                type="info"
                                plain
                                @click="toAddLike(reply.id)"
                                style="
                                  background-color: transparent;
                                  margin-left: 10px;
                                  border: none;
                                "
                              >
                                {{ likeList[reply.id] == 1 ? '❤️' : '♡' }}
                              </el-button>
                              <span
                                v-for="countList in likeCountList"
                                :key="countList.commentId"
                              >
                                <span v-if="countList.commentId == reply.id">
                                  {{ countList.likeCount }}人赞了该评论
                                </span>
                              </span>
                              <span style="margin-left: auto">
                                {{ formatTime(reply.createTime) }}
                              </span>
                            </div>
                          </div>
                          <el-divider></el-divider>
                        </div>
                      </div>
                      <div v-else>
                        <p class="text item">暂无回复</p>
                      </div>
                    </el-card>
                    <el-divider></el-divider>
                  </div>
                </div>
              </div>
              <div v-else>
                <p style="text-align: center">没有评论，快来发表评论吧！</p>
              </div>
            </div>
          </el-card>
        </el-main>
      </div>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import throttle from 'lodash/throttle'
// 点赞功能
// 置顶功能
import {
  addComment,
  addLike,
  countLikes,
  getReplyComment,
  isLike,
  isTop,
  taskAddReplyComment,
  taskComment,
  toChangeTop,
  allChat
} from '@/api/comment'
// 在组件挂载时获取任务列表数据
import { onMounted, ref } from 'vue'
import { getStudentTasks } from '@/api/task'
import { Picture } from '@element-plus/icons-vue'
import { ElLoading, ElMessage, ElUpload } from 'element-plus'
import userInfo from '@/stores/userInfo.js'
// 定义各种响应式数据
const userInfoStore = userInfo()
const username = sessionStorage.getItem('user')
const taskList = ref([])
const input = ref('')
const commentList = ref([])
const likeCountList = ref([])
const input1 = ref('')
const taskID = ref('')
const currentTitle = ref('')
const dialogVisible = ref({})
const likeList = ref({})
const selectedTaskId = ref(null)
const isLoading = ref(false)
const fullscreenLoading = ref(false)
const imageUrl = ref('')
const imageUrl1 = ref('')
const chatList = ref([])
const relatedDialogVisible = ref(false)
//查看对话
const currentCommentIdForDialog = ref(null)
const formatTime = timeArray => {
  const date = new Date(
    timeArray[0],
    timeArray[1] - 1,
    timeArray[2],
    timeArray[3],
    timeArray[4],
    timeArray[5]
  )
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始计数，需加1并补0
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const showRelatedDialog = async commentId => {
  currentCommentIdForDialog.value = commentId // 添加这行代码，记录当前点击的评论id
  try {
    const response = await allChat(commentId)
    if (response && response.data) {
      chatList.value = response.data
    } else {
      chatList.value = []
    }
    relatedDialogVisible.value = true
  } catch (error) {
    console.error(error)
  }
}

// 切换评论回复显示隐藏的方法
const toggleReply = async comment => {
  comment.showReply = !comment.showReply
  if (comment.showReply && !comment.replyList) {
    await taskAllReplyComment(taskID.value, comment.id)
  }
  dialogVisible.value[comment.id] = false
}

// 发表新评论的方法，使用节流限制提交频率
const addnewComment = throttle(async taskId => {
  if (username) {
    const commentAreaWrapper = document.getElementById('comment-area-wrapper1')
    const loading = ElLoading.service({
      lock: true,
      text: '评论中',
      background: 'rgb(255,255,255)',
      fullscreen: false,
      target: commentAreaWrapper // 指定加载效果显示的目标元素为评论区包裹元素
    })
    if (input.value.trim() === '') {
      ElMessage.error('评论内容不能为空')
      return
    }
    isLoading.value = true
    console.log('发表评论中...' + imageUrl1.value)
    try {
      // 构建包含评论内容和图片URL（如果有）的评论数据对象
      const commentData = {
        username: username,
        content: input.value,
        taskId: taskId,
        commentPic: imageUrl1.value // 将图片URL添加到评论数据中
      }
      let result = await addComment(commentData) // 使用修改后的评论数据发送请求
      if (result) {
        const response = await taskComment(taskId)
        if (response && response.data) {
          commentList.value = response.data
        } else {
          commentList.value = []
        }
        input.value = ''
        imageUrl.value = '' // 提交成功后清空图片URL，方便下次上传新图片
        ElMessage.success(result.msg ? result.msg : '评论成功')
        await taskAllComment1(taskId)
        setTimeout(() => {
          loading.close()
        }, 2500)
        isLoading.value = false
      }
    } catch (error) {
      console.error('发表评论出现错误:', error)
      ElMessage.error('提交评论失败')
      isLoading.value = false
    }
  } else {
    ElMessage.error('请先登录')
  }
}, 5000)

onMounted(async () => {
  try {
    const response = await getStudentTasks(userInfoStore.info.id)
    if (response && response.data) {
      taskList.value = response.data
      console.log(taskList.value)
    } else {
      taskList.value = []
    }
  } catch (error) {
    console.error('获取任务列表出现错误:', error)
    ElMessage.error('获取任务列表失败')
  }
})

// 获取指定任务的评论列表以及相关状态信息（点赞、置顶等）
// 获取指定任务的评论列表以及相关状态信息（点赞、置顶等）
const taskAllComment = throttle(async taskId => {
  const commentAreaWrapper = document.getElementById('comment-area-wrapper')
  const loading = ElLoading.service({
    lock: true,
    text: '评论区加载中',
    background: 'rgb(245,245,245)',
    fullscreen: false,
    target: commentAreaWrapper // 指定加载效果显示的目标元素为评论区包裹元素
  })
  selectedTaskId.value = taskId
  taskID.value = taskId
  const taskItem = taskList.value.find(item => item.taskId === taskId)
  const responseForLike = await countLikes(taskId)
  currentTitle.value = taskItem ? taskItem.taskDescription : '评论区'
  try {
    const response = await taskComment(taskId)
    if (response && Array.isArray(response.data)) {
      commentList.value = response.data.map(comment => ({
        ...comment,
        showReply: false,
        isTop: false,
        topButtonText: '置顶'
      }))
      likeCountList.value = responseForLike.data

      await Promise.all(
        commentList.value.map(async comment => {
          const isLikedResult = await isLike(comment.id, username)
          likeList.value[comment.id] = isLikedResult.data === 1 ? '1' : '0'
          const isTopResult = await isTop(comment.id)
          comment.isTop = isTopResult.data === 1
          comment.topButtonText = comment.isTop ? '取消置顶' : '置顶'
        })
      )

      commentList.value.sort((a, b) => b.isTop - a.isTop)
      isLoading.value = false
    } else {
      commentList.value = []
      console.warn('没有找到评论数据')
      isLoading.value = false
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取评论失败')
    isLoading.value = false
  }
  setTimeout(() => {
    loading.close()
  }, 2500)
}, 1000)
const taskAllComment1 = throttle(async taskId => {
  selectedTaskId.value = taskId
  taskID.value = taskId
  const taskItem = taskList.value.find(item => item.taskId === taskId)
  const responseForLike = await countLikes(taskId)
  currentTitle.value = taskItem ? taskItem.taskDescription : '评论区'
  try {
    const response = await taskComment(taskId)
    if (response && Array.isArray(response.data)) {
      commentList.value = response.data.map(comment => ({
        ...comment,
        showReply: false,
        isTop: false,
        topButtonText: '置顶'
      }))
      likeCountList.value = responseForLike.data

      await Promise.all(
        commentList.value.map(async comment => {
          const isLikedResult = await isLike(comment.id)
          likeList.value[comment.id] = isLikedResult.data === 1 ? '1' : '0'
          const isTopResult = await isTop(comment.id)
          comment.isTop = isTopResult.data === 1
          comment.topButtonText = comment.isTop ? '取消置顶' : '置顶'
        })
      )

      commentList.value.sort((a, b) => b.isTop - a.isTop)
      isLoading.value = false
    } else {
      commentList.value = []
      console.warn('没有找到评论数据')
      isLoading.value = false
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取评论失败')
    isLoading.value = false
  }
}, 1000)
// 添加回复评论的方法
const addReplyComment = async (taskId, id, level, parentCommentId) => {
  if (username) {
    try {
      const result = await taskAddReplyComment({
        username: username,
        taskId,
        id,
        level,
        parentCommentId,
        content: input1.value,
        commentPic: imageUrl1.value
      })
      console.log('返回的完整回复数据:', result)
      return result
    } catch (error) {
      console.error('添加回复失败:', error)
      return null
    }
  } else {
    ElMessage.error('请先登录')
  }
}

// 获取指定评论的所有回复评论数据
const taskAllReplyComment = async (selectedTaskId, commentid) => {
  try {
    const replyResponse = await getReplyComment(selectedTaskId, commentid)
    const comment = commentList.value.find(item => item.id === commentid)
    if (replyResponse && replyResponse.data) {
      comment.replyList = replyResponse.data
      await Promise.all(
        comment.replyList.map(async reply => {
          const isLikedResult = await isLike(reply.id)
          likeList.value[reply.id] = isLikedResult.data === 1 ? '1' : '0'
        })
      )
    } else {
      comment.replyList = []
    }
  } catch (error) {
    console.error('获取回复失败:', error)
    ElMessage.error('获取回复失败')
  }
}

// 处理评论回复按钮点击事件的方法
const handleCommentReplyComment = async (
  taskId,
  id,
  level,
  parentCommentId
) => {
  dialogVisible.value[id] = false
  const result = await addReplyComment(taskId, id, level, parentCommentId)
  const comment = commentList.value.find(item => item.id === id)
  comment.replyList.value = await getReplyComment(taskId, id)
  if (result) {
    if (comment.replyList) {
      await taskAllReplyComment(taskId, id)
    } else {
      ElMessage.error('评论不存在')
    }
    ElMessage.success('回复成功')
  } else {
    ElMessage.error('回复失败，请重试')
  }
  input1.value = ''
}

// 处理回复的回复按钮点击事件的方法
const handleReplyReplyComment = async (taskId, id, level, parentCommentId) => {
  dialogVisible.value[id] = false
  const result = await addReplyComment(taskId, id, level, parentCommentId)

  if (result) {
    const comment = commentList.value.find(item => item.id === parentCommentId)
    if (comment) {
      await taskAllReplyComment(taskId, parentCommentId)
      ElMessage.success('回复成功')
    } else {
      ElMessage.error('评论不存在')
    }
  } else {
    ElMessage.error('回复失败，请重试')
  }
  input1.value = ''
}

const toAddLike = throttle(async commentId => {
  if (username) {
    const result = await addLike(commentId, username)
    if (result.data == '2' || result.data == '0') {
      likeList.value[commentId] = '1'
      ElMessage.success('点赞成功')
      // 点赞成功时更新点赞计数
      try {
        const responseForLike = await countLikes(selectedTaskId.value)
        if (responseForLike && responseForLike.data) {
          likeCountList.value = responseForLike.data
        }
      } catch (error) {
        console.error('获取点赞计数失败:', error)
      }
    } else {
      likeList.value[commentId] = '0'
      // 添加以下代码，取消点赞时同样更新点赞计数
      try {
        const responseForLike = await countLikes(selectedTaskId.value)
        if (responseForLike && responseForLike.data) {
          likeCountList.value = responseForLike.data
        }
      } catch (error) {
        console.error('获取点赞计数失败:', error)
      }
    }
  } else {
    ElMessage.error('请先登录')
  }
}, 1500)

const handleTop = async commentId => {
  const commentAreaWrapper = document.getElementById('comment-area-wrapper1')
  const loading = ElLoading.service({
    lock: true,
    text: '置顶变化中',
    background: 'rgb(255,255,255)',
    fullscreen: false,
    target: commentAreaWrapper, // 指定加载效果显示的目标元素为评论区包裹元素
    customClass: 'custom-loading-style'
  })
  const result = await toChangeTop(commentId)
  setTimeout(() => {
    loading.close()
  }, 2500)
  if (result.data == 1) {
    ElMessage.success('置顶成功')
  } else {
    ElMessage.error('取消置顶')
  }
  const currentTaskId = selectedTaskId.value
  if (currentTaskId) {
    await taskAllComment1(currentTaskId)
  }
}

// 上传前的钩子函数，这里可以做一些文件类型、大小等验证，暂时简单返回true表示允许上传
const beforeUpload = file => {
  const isJPEG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  if (!(isJPEG || isPNG)) {
    ElMessage.error('只能上传 JPEG 或 PNG 格式的图片')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 上传成功后的回调函数，将返回的图片URL保存到imageUrl变量中
const handleUploadSuccess = response => {
  imageUrl.value = response // response即为后端返回的图片URL，保存起来以便后续和评论一起提交
}
import request from '@/utils/request'
const customUpload = async options => {
  if (username) {
    const { file, onSuccess, onError } = options
    try {
      const formData = new FormData()
      formData.append('file', file)
      const response = await request.post('/commentPicture', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      console.log(
        '上传图片返回的完整信息（类型及内容）:',
        typeof response,
        response
      )
      imageUrl1.value = response.data
      // 判断返回值类型是否为字符串，如果是则按字符串进行处理
      if (typeof response === 'string') {
        console.log('上传图片返回的是字符串类型的URL:', response)
        const successResponseObject = {
          file: file, // 保持上传的原始文件对象
          response: {
            status: 200, // 假设成功状态码为200，根据实际情况调整
            data: response,
            message: '图片添加成功'
          }
        }
        onSuccess(successResponseObject)
      } else {
        console.log('上传图片返回的是非字符串类型的数据，按常规对象等逻辑处理')

        onSuccess(response.data)
      }
    } catch (error) {
      console.error('上传图片出现错误，详细错误信息:', error)
      onError(error)
    }
  } else {
    ElMessage.error('请先登录')
  }
}

const handleDialogClose = () => {
  const commentId = document.querySelector('.el-dialog[data-comment-id]')
    ?.dataset.commentId
  if (commentId) {
    // 在这里可以根据获取到的commentId做一些后续操作，比如重置相关数据等
    console.log(`关闭了评论 ${commentId} 的对话详情对话框`)
  }
  relatedDialogVisible.value = false
}
</script>

<style scoped>
/* 评论区相关基础样式设置 */
.task-list {
  height: 800px; /* 根据需要设置高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}

.comment-section {
  height: 800px; /* 根据需要设置高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}
</style>
